﻿using UnityEngine;
using System.Collections;

public enum RTPawnState
{
	Idle,
	Walk,
	WalkToAttack,
	Attack,
}

public class RTPawnManifest : MonoBehaviour {

	Animation anim;
	BattleCharInfo charInfo;
	Vector3 moveToPosition;
	RTPawnState pawnState;
	RTPawnManifest targetManifest;

	public float charMoveSpeed = 2;
	public float walkAnimSpeed = 2;

	void Start()
	{
		charInfo = GetComponent<BattleCharInfo>();
		BattleResManager.AttachWeapon( this.gameObject, charInfo, null, false);

		anim = GetComponent<Animation>();
		anim.Play();
		//RTBattle.Instance.mainCharManifest = this;
		moveToPosition = transform.position;
		pawnState = RTPawnState.Idle;
		Debug.Log( anim["walk01"].wrapMode  +"   "+anim["walk01"].speed);
		anim["walk01"].speed = walkAnimSpeed;
		anim["walk01"].wrapMode = WrapMode.Loop;
	}

	void StateAttack()
	{
		Vector3 targetPos = targetManifest.transform.position;
		targetPos.y=0;
		transform.LookAt(targetPos);
		pawnState= RTPawnState.Attack;
		anim.CrossFade("attack01",0.2f);
		anim.CrossFadeQueued("idle01");
	}

	void StateIdle()
	{
		pawnState = RTPawnState.Idle;
		anim.CrossFade("idle01",0.2f);
	}

	void StateWalk()
	{
		pawnState = RTPawnState.Walk;
		anim.CrossFade("walk01",0.2f);
	}

	void StateAttackMove()
	{
		pawnState = RTPawnState.WalkToAttack;
		anim.CrossFade("walk01",0.2f);
	}

	public void MoveTo(Vector3 _toPos)
	{
		StateWalk();
		moveToPosition = _toPos;
		moveToPosition.y=0;
		//Quaternion quat = Quaternion.LookRotation( moveToPosition - transform.position);
		//if(quat.IsValid())
		//	transform.rotation = quat;
		transform.LookAt(moveToPosition);
	}

	public void AttackTo(RTPawnManifest _target)
	{
		targetManifest = _target;
		StateAttackMove();
		moveToPosition = BattleUtil.GetTargetAttackPos(transform.position, _target.transform.position, charInfo.myRadius + _target.charInfo.myRadius);
		moveToPosition.y=0;
		transform.LookAt(moveToPosition);
	}

	void Update()
	{
		if(pawnState== RTPawnState.Walk || pawnState== RTPawnState.WalkToAttack) {
			transform.position = transform.position + transform.forward * charMoveSpeed * Time.deltaTime;
			if(  Vector3.SqrMagnitude( transform.position - moveToPosition) < 0.1f) {
				if(pawnState== RTPawnState.Walk)
					StateIdle();
				else
					StateAttack();
			}
		}

	}

//	void OnGUI()
//	{
//		if (GUI.Button(  new Rect(100, 200, 80 , 30), "Attack")  )
//		{
//			Attack();
//		}
//	}
}
